package xiaoqianlang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import xiaoqianlang.common.ApiResponse;
import xiaoqianlang.pojo.User;
import xiaoqianlang.service.UserService;
import xiaoqianlang.util.JwtUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：xiaoqianlang
 * @Package：xiaoqianlang.controller
 * @Project：PasswordManage
 * @name：AuthController
 * @Date：2025/4/3/周四 15:58
 * @Filename：AuthController
 */

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册接口
     */
    @PostMapping(value = "/register",
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE},
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<String> register(@RequestParam(required = false) String username,
                                        @RequestParam(required = false) String email,
                                        @RequestParam(required = false) String password,
                                        @RequestBody(required = false) Map<String, String> requestBody) {
        try {
            // 如果是 JSON 请求，则从 requestBody 中获取参数
            if (requestBody != null) {
                username = requestBody.get("username");
                email = requestBody.get("email");
                password = requestBody.get("password");
            }

            // 检查参数是否为空
            if (username == null || email == null || password == null) {
                return ApiResponse.error("请求参数不完整！");
            }

            userService.register(username, email, password);
            return ApiResponse.success("注册成功！");
        } catch (Exception e) {
            return ApiResponse.error("注册失败：" + e.getMessage());
        }
    }

    /**
     * 用户登录接口
     */
    @PostMapping(value = "/login",
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE},
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<Map<String, Object>> login(@RequestParam(required = false) String usernameOrEmail,
                                                  @RequestParam(required = false) String password,
                                                  @RequestBody(required = false) Map<String, String> requestBody) {
        try {
            // 如果是 JSON 请求，则从 requestBody 中获取参数
            if (requestBody != null) {
                usernameOrEmail = requestBody.get("usernameOrEmail");
                password = requestBody.get("password");
            }

            // 检查参数是否为空
            if (usernameOrEmail == null || password == null) {
                return ApiResponse.error("请求参数不完整！");
            }

            User user = userService.login(usernameOrEmail, password);

            // 生成 JWT Token
            String token = JwtUtil.generateToken(user.getId(), user.getUsername());

            // 返回用户信息和 Token
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("user", user);
            responseData.put("token", token);
            return ApiResponse.success(responseData);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    /**
     * 根据 ID 获取用户信息
     */
    @GetMapping(value = "/info/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            if (user == null) {
                return ApiResponse.error("用户不存在！");
            }
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户名获取用户信息
     */
    @GetMapping(value = "/info/username", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<User> getUserByUsername(@RequestParam String username) {
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return ApiResponse.error("用户不存在！");
            }
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据邮箱获取用户信息
     */
    @GetMapping(value = "/info/email", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<User> getUserByEmail(@RequestParam String email) {
        try {
            User user = userService.getUserByEmail(email);
            if (user == null) {
                return ApiResponse.error("用户不存在！");
            }
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error("获取用户信息失败：" + e.getMessage());
        }
    }
}

